//
//  ExportViewController.m
//  ProfilePicture
//
//  Created by 张云江 on 2019/10/17.
//  Copyright © 2019年 张云江. All rights reserved.
//

#import "ExportViewController.h"
#import "VipViewController.h"

@interface ExportViewController () <YQInAppPurchaseToolDelegate>
{
    ZHProgressHUD  *progressHUD;
}
@property(nonatomic,strong)UIImageView      *photoImage;
@property(nonatomic,strong)UIImageView      *photoArrImage;

@end

@implementation ExportViewController

+ (ExportViewController *)initWtihCutCheckPicInfo:(CutCheckPicInfo *)info
{
    ExportViewController *vc = [[ExportViewController alloc]init];
    vc.info = info;
    return vc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
}

- (void)setNav
{
    self.customNavBar.title = [NSString stringWithFormat:@"导出"];
    self.customNavBar.backgroundColor = kUIColorFromRGB(0x2F54EB);
}

- (void)creatUI
{
    self.view.backgroundColor = kUIColorFromRGB(0xF3F5FF);
    
    self.photoImage = [[UIImageView alloc] init];
    self.photoImage.backgroundColor = kUIColorFromRGB(0xD8D8D8);
    [self.view addSubview:self.photoImage];
    [self.photoImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(kRatio(78));
        make.right.equalTo(self.view).offset(kRatio(-78));
        make.top.equalTo(self.view).offset(kNavigationHeight + kRatio(20));
        make.height.mas_equalTo(kRatio(290));
    }];
    
    [self.photoImage sd_setImageWithURL:[NSURL URLWithString:self.info.img_wm_url_list[WCDelegate.currbgCount]]];
    
    self.photoArrImage = [[UIImageView alloc] init];
    self.photoArrImage.backgroundColor = kUIColorFromRGB(0xD8D8D8);
    [self.view addSubview:self.photoArrImage];
    [self.photoArrImage mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(kRatio(108));
        make.right.equalTo(self.view).offset(kRatio(-108));
        make.top.equalTo(self.photoImage.mas_bottom).offset(kRatio(20));
        make.height.mas_equalTo(kRatio(98));
    }];
    if (self.info.print_wm_url_list.count == 0) {
        self.photoArrImage.hidden = YES;
    } else {
        [self.photoArrImage sd_setImageWithURL:[NSURL URLWithString:self.info.print_wm_url_list[WCDelegate.currbgCount]]];
    }
    
    UIView *footBg = [[UIView alloc]init];
    [self.view addSubview:footBg];
    footBg.backgroundColor = [UIColor whiteColor];
    footBg.layer.cornerRadius = kRatio(26);
    footBg.layer.masksToBounds = YES;
    footBg.layer.shadowOffset = CGSizeMake(0,2);
    footBg.layer.shadowOpacity = 1;
    footBg.layer.shadowRadius = 8;
    [footBg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(kRatio(26));
        make.height.mas_equalTo(kRatio(154 + 26));
    }];
    
    CustomBtn *cusBtn1 = [[CustomBtn alloc]init];
    [cusBtn1 setCustom5BtnwtihNormal:@"¥3.00" withLabel:@"导出指定背景电子照"];
    [cusBtn1 addTarget:self action:@selector(onBuy3Click) forControlEvents:UIControlEventTouchUpInside];
    [footBg addSubview:cusBtn1];
    [cusBtn1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(footBg).offset(kRatio(20));
        make.top.equalTo(footBg).offset(kRatio(20));
        make.width.mas_equalTo(kRatio(158));
        make.height.mas_equalTo(kRatio(64));
    }];
    
    CustomBtn *cusBtn2 = [[CustomBtn alloc]init];
    [cusBtn2 setCustom5BtnwtihNormal:@"¥8.00" withLabel:@"导出全部背景电子照"];
    [cusBtn2 addTarget:self action:@selector(onBuy8Click) forControlEvents:UIControlEventTouchUpInside];
    [footBg addSubview:cusBtn2];
    [cusBtn2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(footBg).offset(kRatio(-20));
        make.top.equalTo(footBg).offset(kRatio(20));
        make.width.mas_equalTo(kRatio(158));
        make.height.mas_equalTo(kRatio(64));
    }];
    
    UIButton *VipBtn = [[UIButton alloc]init];
    [VipBtn setTitle:[NSString stringWithFormat:@"保存图片"] forState:UIControlStateNormal];
    [VipBtn addTarget:self action:@selector(onVipBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [VipBtn setBackgroundColor:kUIColorFromRGB(0x2F54EB)];
    [self.view addSubview:VipBtn];
    [VipBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(kScreenWidth);
        make.bottom.left.equalTo(self.view);
        make.height.mas_equalTo(kRatio(50));
    }];
}

- (void)onVipBtnClick
{
    if (kVipBool) {
        [self saveImage];
    } else {
        VipViewController *vc = [[VipViewController alloc]init];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)onBuy3Click
{
    YQInAppPurchaseTool *IAPTool = [YQInAppPurchaseTool defaultTool];
    IAPTool.delegate = self;
    [IAPTool requestProductsWithProductArray:@[@"com.yhjy.ProfilePicture_new_2"]];
}

- (void)onBuy8Click
{
    YQInAppPurchaseTool *IAPTool = [YQInAppPurchaseTool defaultTool];
    IAPTool.delegate = self;
    [IAPTool requestProductsWithProductArray:@[@"com.yhjy.ProfilePicture_new_3"]];
}

#pragma mark - YQInAppPurchaseToolDelegate
- (void)IAPToolGotProducts:(NSMutableArray *)products {
    NSLog(@"商品信息 = %@",[[products firstObject] mj_keyValues]);
    if (products.count > 0) {
        [self BuyProduct:[products firstObject]];
    } else {
        [ZHProgressHUD hideHUD];
        [MBProgressHUD showError:@"商品信息不存在"];
    }
}

//购买商品
- (void)BuyProduct:(SKProduct *)product
{
    [[YQInAppPurchaseTool defaultTool] buyProduct:product.productIdentifier];
}

//取消购买
- (void)IAPToolCanceldWithProductID:(NSString *)productID
{
    NSLog(@"取消购买==%@",productID);
    [ZHProgressHUD hideHUD];
    [MBProgressHUD hideHUD];
}

//购买成功，开始验证购买
- (void)IAPToolBeginCheckingdWithProductID:(NSString *)productID
{
    NSLog(@"BeginChecking:%@",productID);
    progressHUD = [ZHProgressHUD showMessage:@"正在购买"];
    [self performSelector:@selector(onJoinFailed) withObject:nil afterDelay:20.0f];
}

//验证失败
- (void)IAPToolCheckFailedWithProductID:(NSString *)productID andInfo:(NSData *)infoData
{
    NSLog(@"CheckFailed:%@",productID);
    [ZHProgressHUD hideHUD];
    [MBProgressHUD showError:@"验证失败"];
}

//重复验证
- (void)IAPToolCheckRedundantWithProductID:(NSString *)productID
{
    NSLog(@"CheckRedundant:%@",productID);
    [ZHProgressHUD hideHUD];
    [MBProgressHUD showError:@"重复验证"];
}

//购买成功
- (void)IAPToolBoughtProductSuccessedWithProductID:(NSString *)productID andInfo:(NSDictionary *)infoDic
{
    NSLog(@"BoughtSuccessed:%@",productID);
    NSLog(@"successedInfo:%@",infoDic);
    [ZHProgressHUD hideHUD];
    [MBProgressHUD showSuccess:@"购买成功"];
    if ([productID isEqualToString:@"com.yhjy.ProfilePicture_new_2"]) {
        [self saveImage];
    } else if ([productID isEqualToString:@"com.yhjy.ProfilePicture_new_3"]) {
        [self saveAllImage];
    } else if ([productID isEqualToString:@"com.yhjy.ProfilePicture_new_1"]) {
        [self vipDeadlineProductID:productID];
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"vipBool"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        if (self.navigationController) {
            [self.navigationController popViewControllerAnimated:YES];
        } else {
            [self dismissViewControllerAnimated:YES completion:nil];
        }
        [self saveAllImage];
    }
}

//恢复已购买的商品
- (void)restoreProduct
{
    [ZHProgressHUD showMessage:@"正在恢复商品"];
    [[YQInAppPurchaseTool defaultTool] restorePurchase];
}

//恢复了已购买的商品（仅限永久有效商品）
- (void)IAPToolRestoredProductID:(NSString *)productID
{
    NSLog(@"Restored:%@",productID);
    [ZHProgressHUD hideHUD];
    [MBProgressHUD showSuccess:@"成功恢复了商品"];
    [self vipDeadlineProductID:productID];
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"vipBool"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if (self.navigationController) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}

- (void)vipDeadlineProductID:(NSString *)productID
{
    NSString *date;
    if ([productID isEqualToString:@"com.yhjy.ProfilePicture_new_1"]) {
        date = [self getNDay:[NSDate daysInMonthFromDate:[NSDate date]]];
    }
    [[NSUserDefaults standardUserDefaults] setObject:date forKey:@"Date"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (NSString *)getNDay:(NSInteger)n
{
    NSDate *nowDate = [NSDate date];
    NSDate *theDate;
    if (n != 0) {
        NSTimeInterval  oneDay = 24*60*60*1;
        theDate = [nowDate initWithTimeIntervalSinceNow: oneDay*n ];
    } else {
        theDate = nowDate;
    }
    NSDateFormatter *date_formatter = [[NSDateFormatter alloc] init];
    [date_formatter setDateFormat:@"yyyy-MM-dd"];
    NSString *the_date_str = [date_formatter stringFromDate:theDate];
    return the_date_str;
}

- (void)saveAllImage
{
    [ZHProgressHUD showMessage:@"正在保存图片"];
    dispatch_group_t group = dispatch_group_create();
    NSMutableArray *arr_m = [NSMutableArray array];
    [arr_m addObjectsFromArray:self.info.file_name];
    [arr_m addObjectsFromArray:self.info.file_name_print];
    for (int i = 0; i < arr_m.count; i++) {
        dispatch_group_enter(group);
        [[NetworkMgr shareInstance] postwithImageName:arr_m[i] success:^(NSData * _Nonnull data) {
            dispatch_group_leave(group);
            [self loadImageFinished:[UIImage imageWithData:data]];
        } failure:^(NSError * _Nonnull error) {
            dispatch_group_leave(group);
        }];
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [ZHProgressHUD hideHUD];
        [MBProgressHUD showSuccess:@"保存图片成功"];
    });
}

- (void)saveImage
{
    [ZHProgressHUD showMessage:@"正在保存图片"];
    dispatch_group_t group = dispatch_group_create();
    if (self.info.file_name.count > 0) {
        dispatch_group_enter(group);
        [[NetworkMgr shareInstance] postwithImageName:self.info.file_name[WCDelegate.currbgCount] success:^(NSData * _Nonnull data) {
            dispatch_group_leave(group);
            [self loadImageFinished:[UIImage imageWithData:data]];
        } failure:^(NSError * _Nonnull error) {
            dispatch_group_leave(group);
        }];
    }
    
    if (self.info.file_name_print.count > 0) {
        dispatch_group_enter(group);
        [[NetworkMgr shareInstance] postwithImageName:self.info.file_name_print[WCDelegate.currbgCount] success:^(NSData * _Nonnull data) {
            dispatch_group_leave(group);
            [self loadImageFinished:[UIImage imageWithData:data]];
        } failure:^(NSError * _Nonnull error) {
            dispatch_group_leave(group);
        }];
    }
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        [ZHProgressHUD hideHUD];
        [MBProgressHUD showSuccess:@"保存图片成功"];
    });
}

- (PHAssetCollection *)creatImagePath
{
    NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"];
    PHFetchResult<PHAssetCollection *> *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    PHAssetCollection *appCollection = nil;
    for (PHAssetCollection *collection in collections) {
        if ([collection.localizedTitle isEqualToString:appName]) {
            appCollection = collection;
            break;
        }
    }
    if (appCollection == nil) {
        NSError *error = nil;
        __block NSString *createCollectionID = nil;
        [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
            NSString *appName = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"];
            createCollectionID = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:appName].placeholderForCreatedAssetCollection.localIdentifier;
        } error:&error];
        if (error) {
        } else {
            appCollection = [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[createCollectionID] options:nil].firstObject;
        }
    }
    return appCollection;
}

- (void)loadImageFinished:(UIImage *)image
{
    __block PHObjectPlaceholder *placeholderForCreatedAsset;
    NSError *error = nil;
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        placeholderForCreatedAsset = [PHAssetChangeRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset;
    } error:&error];
    if (error) {
        return;
    }
    PHAssetCollection *createCollection = [self creatImagePath];
    if (createCollection == nil) {
        return;
    }
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:createCollection];
        [request insertAssets:@[placeholderForCreatedAsset] atIndexes:[NSIndexSet indexSetWithIndex:0]];
    } error:&error];
    
}

- (void)onJoinFailed
{
    [progressHUD hideHUD];
}
@end
